// 为了便于维护 这个超级大项目 路由守卫抽离出来
import router, { asyncRoutes } from './router'
// import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // 导入进度条的包
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import store from '@/store'
// import user from 'mock/user'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      try {
        if (!store.getters.userId) {
          const res = await store.dispatch('user/getUserInfo')
          // console.log(res.roles.menus, '守卫')
          const userRoutes = asyncRoutes.filter(item => {
            if (res.roles.menus.includes(item.name)) {
              return true
            } else {
              return false
            }
          })
          store.commit('user/setRoutes', userRoutes)
          console.log(userRoutes, '用户专属路由规则')
          router.addRoutes(
            [
              ...userRoutes,
              { path: '*', redirect: '/404', hidden: true }
            ]
          )
          next(to.path) // 重进当前页面
          return
        }
        next()
      } catch (error) {
        // token过期，清除token和用户信息
        store.commit('user/logout')
        next(`/login`)
        NProgress.done()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next(`/login`)
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
